import * as Koa from 'koa';
import md5 = require('md5');
import { Guid, route, RouteOptionsVerify, ServiceManager, UsingLock } from "../../common";
import { ServiceException } from '../../common/excpetion';
import { Account } from '../../domain/models/account';
import { AccountService } from '../../service/AccountService';
const accountSvr = ServiceManager.Current.GetService<AccountService>('AccountService');

class AccountController {
    @route(new RouteOptionsVerify('GET', '/api/account'))
    async queryAccounts(ctx: Koa.Context, next) {
        let params = ctx.query;
        let data = await accountSvr.QueryAccount(params);
        ctx.response.body = data;
        await next();
    }
    @route(new RouteOptionsVerify('GET', '/api/account/:id'))
    async getAccountInfoById(ctx: Koa.Context, next) {
        let id = ctx.params.id;
        let data = await accountSvr.GetAccountById(id);
        ctx.response.body =data;
        await next();
    }
    @route(new RouteOptionsVerify('POST', '/api/account'))
    async createAccount(ctx: Koa.Context, next) {
        let account:Account = ctx.request.body;
        account.id = Guid.GetGuid();
        account.password=md5(account.password);
        let userResult = await accountSvr.CreateAccount(account);
        ctx.response.body =userResult;
        await next();
    }
    @route(new RouteOptionsVerify('PUT', '/api/account'))
    async updateAccount(ctx: Koa.Context, next) {
        let acc =ctx.request.body;
        if(!acc.id){
            throw new ServiceException('id 不能为空！', 'not_be_null');
        }
       
        await UsingLock(acc.id, async () => {
            let accResult = await accountSvr.UpdateAccount(acc);
            ctx.response.body = accResult;
        });

        await next();
    }
    @route(new RouteOptionsVerify('DELETE', '/api/account/:id'))
    async deleteAccount(ctx: Koa.Context, next) {
        let id = ctx.params.id;
        let account = await accountSvr.GetAccountById(id);
        account.isDelete=true;

        await UsingLock(account.id, async () => {
           ctx.response.body = await accountSvr.UpdateAccount(account);
        });
        await next();
    }
}